package com.hengxinguotong.zhihuichengjian.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.ConstructionScheduleAdapter;
import com.hengxinguotong.zhihuichengjian.adapter.WorkTrendAdapter;
import com.hengxinguotong.zhihuichengjian.bean.Build;
import com.hengxinguotong.zhihuichengjian.bean.BuildRes;
import com.hengxinguotong.zhihuichengjian.bean.ConstructionSchedule;
import com.hengxinguotong.zhihuichengjian.bean.ConstructionScheduleRes;
import com.hengxinguotong.zhihuichengjian.bean.HomePicRes;
import com.hengxinguotong.zhihuichengjian.bean.Message;
import com.hengxinguotong.zhihuichengjian.bean.MessageRes;
import com.hengxinguotong.zhihuichengjian.bean.Quality;
import com.hengxinguotong.zhihuichengjian.bean.QualityRes;
import com.hengxinguotong.zhihuichengjian.bean.Security;
import com.hengxinguotong.zhihuichengjian.bean.SecurityRes;
import com.hengxinguotong.zhihuichengjian.bean.TaskRes;
import com.hengxinguotong.zhihuichengjian.bean.WorkTrendRes;
import com.hengxinguotong.zhihuichengjian.sys.CaptureActivity;
import com.hengxinguotong.zhihuichengjian.ui.HomeActivity;
import com.hengxinguotong.zhihuichengjian.ui.MainActivity;
import com.hengxinguotong.zhihuichengjian.ui.ReadMessageActivity;
import com.hengxinguotong.zhihuichengjian.ui.WebViewActivity;
import com.hengxinguotong.zhihuichengjian.ui.app.BaseFragment;
import com.hengxinguotong.zhihuichengjian.ui.building.ReplyActivity;
import com.hengxinguotong.zhihuichengjian.ui.engineering.reservation.ReservationListActivity;
import com.hengxinguotong.zhihuichengjian.ui.engineering.task.SubmitTaskActivity;
import com.hengxinguotong.zhihuichengjian.ui.quality.RectificationActivity;
import com.hengxinguotong.zhihuichengjian.ui.security.SecurityRectificationActivity;
import com.hengxinguotong.zhihuichengjian.utils.ActivityController;
import com.hengxinguotong.zhihuichengjian.utils.Constants;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.view.NetworkImageView;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 各项目进度
 * Created by Administrator on 2018/2/26.
 */

public class EnterpriseFragment extends BaseFragment implements View.OnClickListener{
    private View rootView = null;
    @BindView(R.id.title_tv)
    HXTextView titleTv;
    @BindView(R.id.list_title_tv)
    HXTextView listTitleTv;
    @BindView(R.id.home_vp)
    ViewPager homeVp;
    @BindView(R.id.point_container)
    LinearLayout pointContainer;
    @BindView(R.id.icon_dongtai)
    ImageView iconDongtai;
    @BindView(R.id.icon_message)
    ImageView iconMessage;
    @BindView(R.id.line_iv)
    ImageView lineIv;
    @BindView(R.id.enterprise_home_rv)
    RecyclerView enterpriseHomeRv;
    @BindView(R.id.refresh_list)
    PullToRefreshLayout refreshList;
    @BindView(R.id.mTopScrollView)
    NestedScrollView mTopScrollView;

    private int marginLeft ;
    private MainActivity mainActivity;
    private boolean isLeft = true;
    private final static int LEFT = 1001, RIGHT = 1002, PICS = 1003;
    private int pageNum = 1;
    private List<ConstructionSchedule> scheduleList;
    private ConstructionScheduleAdapter constructionScheduleAdapter;
    private List<Message> trendList;
    private WorkTrendAdapter workTrendAdapter;
    private List<String> pics;
    private List<NetworkImageView> list;
    private List<Integer> drawables;
    //轮播图当前页
    private int currentPage = 0;
    private boolean isFirst = true;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what){
                case LEFT:
                    scheduleList = (List<ConstructionSchedule>) msg.obj;
                    constructionScheduleAdapter.setDataList(scheduleList);
                    break;
                case RIGHT:
                    List<Message> datas = (List<Message>) msg.obj;
                    addBuildData(datas);
                    break;
                case PICS:
                    initHomeVp();
                    break;
            }
        }
    };

    private void addBuildData(List<Message> datas) {
        if (pageNum == 1)
        {
            refreshList.refreshFinish(PullToRefreshLayout.SUCCEED);
            trendList = datas;
        } else
        {
            refreshList.loadmoreFinish(PullToRefreshLayout.SUCCEED);
            trendList.addAll(datas);
        }
        if (datas.size() >= Utils.ONCECOUNT)
        {
            refreshList.setPullUpEnable(true);
        } else
        {
            refreshList.setPullUpEnable(false);
        }
        workTrendAdapter.setDataList(trendList);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_enterprise_home, null);
        }
        mainActivity = (MainActivity) getActivity();
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    @Override
    public void onLazyLoad() {
        initData();
        queryHomePic(null);
    }

    private void initView(){
        String title = SPUtil.getString(mainActivity, "levelName");
        titleTv.setText(title);

        scheduleList = new ArrayList<>();
        constructionScheduleAdapter = new ConstructionScheduleAdapter(mainActivity, scheduleList);
        constructionScheduleAdapter.setClickListener(scheduleClick);
        trendList = new ArrayList<>();
        workTrendAdapter = new WorkTrendAdapter(mainActivity, trendList);
        workTrendAdapter.setClickListener(trendClick);
        enterpriseHomeRv.setNestedScrollingEnabled(false);
        if(isLeft){
            enterpriseHomeRv.setAdapter(constructionScheduleAdapter);
        }else {
            enterpriseHomeRv.setAdapter(workTrendAdapter);
        }
        enterpriseHomeRv.setLayoutManager(new LinearLayoutManager(mainActivity, LinearLayoutManager.VERTICAL, false));

        refreshList.setPullUpEnable(true);
        refreshList.setOnPullListener(pullListener);
    }

    private void initData(){
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if(isLeft){
                    getConstructionSchedule(null);
                }else{
                    getWorkTrend(null);
                }
            }
        }, 500);
    }

    /**
     * 主页面下拉刷新操作监听
     */
    private PullToRefreshLayout.OnPullListener pullListener = new PullToRefreshLayout.OnPullListener()
    {
        @Override
        public void onRefresh(PullToRefreshLayout pullToRefreshLayout)
        {
            if(isLeft){
                getConstructionSchedule(null);
            }else{
                pageNum = 1;
                getWorkTrend(null);
            }
        }

        @Override
        public void onLoadMore(PullToRefreshLayout pullToRefreshLayout)
        {
            if(isLeft){
                getConstructionSchedule(null);
            }else {
                pageNum = trendList.size() / Utils.ONCECOUNT + 1;
                getWorkTrend(null);
            }
        }
    };

    private ConstructionScheduleAdapter.ClickListener scheduleClick = new ConstructionScheduleAdapter.ClickListener(){
        @Override
        public void onClick(int position) {
            SPUtil.put(mainActivity, "enterpriseName", scheduleList.get(position).getName());
            SPUtil.put(mainActivity, "constructionid", scheduleList.get(position).getConstructionId());
            Intent intent = new Intent(mainActivity, HomeActivity.class);
            startActivity(intent);
        }
    };

    private WorkTrendAdapter.ClickListener trendClick = new WorkTrendAdapter.ClickListener(){
        @Override
        public void onClick(int position) {
            Message message = trendList.get(position);
            Intent intent = new Intent();
            String url = null;
            String uuid = SPUtil.getString(mainActivity, "uuid");
            String constructionid = message.getConstructionId();
            switch (message.getType()){
                case 0://系统消息
                    intent.setClass(mainActivity, ReadMessageActivity.class);
                    intent.putExtra("message", message);
                    startActivityForResult(intent, message.getType());
                    break;
                case 1://质量整改
                case 2://安全整改
                    getSecurityById(message);
                    break;
                case 3://任务派发
                    getTaskById(message);
                    break;
                case 4://预约塔吊
                    intent.setClass(mainActivity, ReservationListActivity.class);
                    intent.putExtra("equipmentType", 1);
                    startActivityForResult(intent, message.getType());
                    break;
                case 5://预约升降机
                    intent.setClass(mainActivity, ReservationListActivity.class);
                    intent.putExtra("equipmentType", 2);
                    startActivityForResult(intent, message.getType());
                    break;
                case 6://工程进度
                    intent.setClass(mainActivity, WebViewActivity.class);
                    url = "/projectSchedule/toProgress/" + uuid + "?constructionId=" + constructionid;
                    intent.putExtra("url", url);
                    intent.putExtra("title", "工程进度");
                    startActivityForResult(intent, message.getType());
                    break;
                case 7://PM10预警
                case 8://噪音预警
                case 11://PM2.5预警
                    intent.setClass(mainActivity, WebViewActivity.class);
                    url = "/environment/toReport/" + uuid + "?constructionId=" + constructionid;
                    intent.putExtra("url", url);
                    intent.putExtra("title", "环境监测");
                    startActivityForResult(intent, message.getType());
                    break;
                case 9://塔吊预警
                    intent.setClass(mainActivity, WebViewActivity.class);
                    url = "/equipmentRegister/toTcDetail/" + uuid + "?constructionId=" + constructionid + "&equipmentId=" + message.getBillId();
                    intent.putExtra("url", url);
                    intent.putExtra("title", "塔吊预警");
                    startActivityForResult(intent, message.getType());
                    break;
                case 10://升降机预警
                    intent.setClass(mainActivity, WebViewActivity.class);
                    url = "/equipmentRegister/toLiftDetail/" + uuid + "?constructionId=" + constructionid + "&equipmentId=" + message.getBillId();
                    intent.putExtra("url", url);
                    intent.putExtra("title", "升降机");
                    startActivityForResult(intent, message.getType());
                    break;
                case 12://现场检查
                    getBuildById(message);//类型.1:质量检查;2:安全检查;3:日常安全检查（目前为传1）
                    break;
                case 13://通知
                    getDetail(message);
                    break;
            }
            setMessageRead(message.getId());
        }
    };

    private void setMessageRead(String id){
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("id", id);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(null, mainActivity, "/message/updateIsRead/" + SPUtil.getString(mainActivity, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if(Utils.isEmpty(json)){
                    return;
                }
                try {
                    JSONObject object = new JSONObject(json);
                    int status = object.getInt("status");
                    String msg = object.getString("msg");
                    if(status == 0){
                        Toast.makeText(mainActivity, msg, Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    Toast.makeText(mainActivity, msg, Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void getTaskById(final Message message){
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("taskId", message.getBillId());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        Utils.requestData("加载中…", mainActivity, "/taskDistribution/queryByTaskId/" + SPUtil.getString(mainActivity, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    TaskRes taskRes = gson.fromJson(json, TaskRes.class);
                    if(taskRes.getStatus() == 1){
                        Intent intent = new Intent();
                        intent.setClass(mainActivity, SubmitTaskActivity.class);
                        intent.putExtra("task", taskRes.getValue());
                        startActivityForResult(intent, message.getType());
                    }else{
                        mainActivity.showToast(taskRes.getMsg());
                    }
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    Toast.makeText(mainActivity, msg, Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void getDetail(final Message message){
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("id", message.getId());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        Utils.requestData("加载中…", mainActivity, "/notice/getDetail/" + SPUtil.getString(mainActivity, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    MessageRes messageRes = gson.fromJson(json, MessageRes.class);
                    if(messageRes.getStatus() == 1){
                        Message notice = messageRes.getValue();
                        if(notice != null ) {
                            Intent intent = new Intent();
                            intent.setClass(mainActivity, ReadMessageActivity.class);
                            intent.putExtra("message", notice);
                            startActivityForResult(intent, message.getType());
                        }else{
                            mainActivity.showToast("通知信息为空");
                        }
                    }else{
                        mainActivity.showToast(messageRes.getMsg());
                    }
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    Toast.makeText(mainActivity, msg, Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void getBuildById(final Message message){
        Utils.requestData("加载中…", mainActivity, "/build/queryByInspectionId/" + SPUtil.getString(mainActivity, "uuid") + "?id=" + message.getBillId(), null, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    BuildRes siteRes = gson.fromJson(json, BuildRes.class);
                    if(siteRes.getStatus() == 1){
                        Build build = siteRes.getValue();
                        if(build != null ) {
                            if(message.getIsRead() == 0){
//                                pushMsg(Constants.QUALITY, build.getCreateBy(), message);
                            }
                            Intent intent = new Intent();
                            intent.setClass(mainActivity, ReplyActivity.class);
                            intent.putExtra("type", Constants.LIVE);
                            intent.putExtra("state", build.getCorrectiveStatus());
                            intent.putExtra("build", build);
                            startActivityForResult(intent, message.getType());
                        }else{
                            mainActivity.showToast("检查单数据为空");
                        }
                    }else{
                        mainActivity.showToast(siteRes.getMsg());
                    }
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    Toast.makeText(mainActivity, msg, Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void getSecurityById(final Message message){
        Utils.requestData("加载中…", mainActivity, "/inspection/queryByInspectionId/" + SPUtil.getString(mainActivity, "uuid") + "?id=" + message.getBillId(), null, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    switch (message.getType()){
                        case 1:
                            QualityRes qualityRes = gson.fromJson(json, QualityRes.class);
                            if(qualityRes.getStatus() == 1){
                                Quality quality = qualityRes.getValue();
                                if(quality != null ) {
                                    Intent intent = new Intent();
                                    intent.setClass(mainActivity, RectificationActivity.class);
                                    intent.putExtra("type", message.getType());
                                    intent.putExtra("quality", quality);
                                    startActivityForResult(intent, message.getType());
                                }else{
                                    mainActivity.showToast("检查单数据为空");
                                }
                            }else{
                                mainActivity.showToast(qualityRes.getMsg());
                            }
                            break;
                        case 2:
                            SecurityRes securityRes = gson.fromJson(json, SecurityRes.class);
                            if(securityRes.getStatus() == 1){
                                Security security = securityRes.getValue();
                                if(security != null ) {
                                    Intent intent = new Intent();
                                    intent.setClass(mainActivity, SecurityRectificationActivity.class);
                                    intent.putExtra("type", message.getType());
                                    intent.putExtra("security", security);
                                    startActivityForResult(intent, message.getType());
                                }else{
                                    mainActivity.showToast("检查单数据为空");
                                }
                            }else{
                                mainActivity.showToast(securityRes.getMsg());
                            }
                            break;
                    }
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    Toast.makeText(mainActivity, msg, Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @OnClick({R.id.scan_iv, R.id.liebiao, R.id.icon_dongtai, R.id.icon_message})
    public void onClick(View v) {
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) lineIv.getLayoutParams();
        Intent intent;
        switch (v.getId()){
            case R.id.icon_dongtai:
                if(!isLeft){
                    isLeft = true;
                    marginLeft = 0;
                    params.leftMargin = marginLeft;
                    listTitleTv.setText("各项目工程进度");
                    iconDongtai.setImageResource(R.mipmap.dongtai_light);
                    iconMessage.setImageResource(R.mipmap.message);
                    enterpriseHomeRv.setAdapter(constructionScheduleAdapter);
                    if(scheduleList.size() == 0){
                        initData();
                    }
                }
                break;
            case R.id.icon_message:
                if(isLeft){
                    isLeft = false;
                    int width = ((LinearLayout)lineIv.getParent()).getWidth();
                    marginLeft = width - lineIv.getWidth();
                    params.leftMargin = marginLeft;
                    listTitleTv.setText("各项目工作动态");
                    iconDongtai.setImageResource(R.mipmap.dongtai);
                    iconMessage.setImageResource(R.mipmap.message_light);
                    enterpriseHomeRv.setAdapter(workTrendAdapter);
                    if(trendList.size() == 0){
                        initData();
                    }
                }
                break;
            case R.id.scan_iv:
                intent = new Intent(mainActivity, CaptureActivity.class);
                startActivity(intent);
                mainActivity.overridePendingTransition(R.anim.activity_in_from_rigth, R.anim.activity_out_to_scale);
                break;
            case R.id.liebiao:
                intent = new Intent(mainActivity, MainActivity.class);
                startActivity(intent);
                ActivityController.finishAll();
                break;
        }
        lineIv.setLayoutParams(params);
    }

    private void queryHomePic(String alert) {
        String orgId = SPUtil.getString(getActivity(), "orgId");
        RequestParams params = new RequestParams();
        params.addBodyParameter("orgId", orgId);
        Utils.requestData(alert, mainActivity, "/home/queryHomePic/" + SPUtil.getString(mainActivity,"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                Gson gson = new Gson();
                HomePicRes homePicRes = gson.fromJson(json, HomePicRes.class);
                if(homePicRes.getStatus() == 1){
                    pics = homePicRes.getValue();
                }else{
                    mainActivity.showToast(homePicRes.getMsg());
                    if (pageNum == 1)
                    {
                        refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                    } else
                    {
                        refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                    }
                }
                handler.sendEmptyMessage(PICS);
            }

            @Override
            public void onFailure(String json) {
                if (pageNum == 1)
                {
                    refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                } else
                {
                    refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                }
                mainActivity.showToast(json);
                handler.sendEmptyMessage(PICS);
            }
        });
    }


    //初始化轮播图
    private void initHomeVp(){
        list = new ArrayList<NetworkImageView>();
        if(pics == null || pics.size() <= 0){
            drawables = new ArrayList<>();
            drawables.add(R.drawable.banner01);
            drawables.add(R.drawable.banner02);
            drawables.add(R.drawable.banner03);
            for (int i = 0; i < drawables.size(); i++) {
                NetworkImageView iv = new NetworkImageView(baseActivity);
                iv.setScaleType(ImageView.ScaleType.FIT_XY);
//                iv.setImageResource(drawables.get(i));
                Glide.with(this)
                        .load(drawables.get(i))
                        .into(iv);
                list.add(iv);
            }
        }else{
            for (int i = 0; i < pics.size(); i++) {
                NetworkImageView iv = new NetworkImageView(baseActivity);
                iv.setScaleType(ImageView.ScaleType.FIT_XY);
                String url = pics.get(i);
//                iv.setImageURL(url);
                Glide.with(this)
                        .load(url)
                        .placeholder(R.drawable.banner01)
                        .error(R.drawable.banner01)
                        .into(iv);
                list.add(iv);
            }
        }
        homeVp.setAdapter(new MyVPAdapter());
        homeVp.setCurrentItem(currentPage);
        homeVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                currentPage = position;
                for (int i = 0; i < pointContainer.getChildCount(); i++) {
                    ImageView imageView = (ImageView) pointContainer.getChildAt(i);
                    if (i == position) {
                        imageView.setImageResource(R.mipmap.round);
                    } else {
                        imageView.setImageResource(R.mipmap.round_hui);
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        if(isFirst){
            initPoints();
            handler.postDelayed(new MyRun(), 2000);
            isFirst = false;
        }
    }

    //初始化轮播图下的小圆点
    private void initPoints(){
        pointContainer.removeAllViews();
        for(int i=0; i<list.size(); i++){
            ImageView dot = new ImageView(baseActivity);
            if(i == currentPage){
                dot.setImageResource(R.mipmap.round);
            }else{
                dot.setImageResource(R.mipmap.round_hui);
            }
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout
                    .LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            if (i > 0) {
                params.leftMargin = 10;//设置圆点边距
            }
            dot.setLayoutParams(params);
            pointContainer.addView(dot);
        }
    }

    //每隔2秒调度轮播图一次
    private class MyRun implements Runnable {

        @Override
        public void run() {
            int item = homeVp.getCurrentItem() + 1;
            homeVp.setCurrentItem(item);
            if (item == list.size()) {
                homeVp.setCurrentItem(0);
            }
            handler.postDelayed(new MyRun(), 3000);
        }
    }

    private class MyVPAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(list.get(position));
            return list.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }

    private void getConstructionSchedule(String alert) {
        Utils.requestData(mainActivity, "/construction/getConstructionSchedule/" + SPUtil.getString(mainActivity,"uuid"),
                null, new Utils.ListenerJson() {
                    @Override
                    public void onSuccess(String json) {
                        Gson gson = new Gson();
                        ConstructionScheduleRes constructionScheduleRes = gson.fromJson(json, ConstructionScheduleRes.class);
                        if(constructionScheduleRes.getStatus() == 1){
                            android.os.Message message = handler.obtainMessage();
                            message.what = LEFT;
                            message.obj = constructionScheduleRes.getValue();
                            message.sendToTarget();
                            if (pageNum == 1)
                            {
                                refreshList.refreshFinish(PullToRefreshLayout.SUCCEED);
                            } else
                            {
                                refreshList.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                            }
                        }else{
                            mainActivity.showToast(constructionScheduleRes.getMsg());
                            if (pageNum == 1)
                            {
                                refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                            } else
                            {
                                refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                            }
                        }
                    }

                    @Override
                    public void onFailure(String json) {
                        if (pageNum == 1)
                        {
                            refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                        } else
                        {
                            refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                        }
                        try {
                            JSONObject object = new JSONObject(json);
                            String msg = object.getString("msg");
                            mainActivity.showToast(msg);
                        } catch (JSONException e) {
                            e.printStackTrace();
                            mainActivity.showToast("系统异常");
                        }
                    }
                });
    }

    private void getWorkTrend (String alert) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("pageNum", pageNum + "");

        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(mainActivity, "/workTrend/queryList/" + SPUtil.getString(mainActivity,"uuid"),
                params, new Utils.ListenerJson() {
                    @Override
                    public void onSuccess(String json) {
                        Gson gson = new Gson();
                        WorkTrendRes workTrendRes = gson.fromJson(json, WorkTrendRes.class);
                        if(workTrendRes.getStatus() == 1){
                            List<Message> datas = workTrendRes.getValue();
                            android.os.Message msg = handler.obtainMessage();
                            msg.obj = datas;
                            msg.what = RIGHT;
                            msg.sendToTarget();
                        }else{
                            mainActivity.showToast(workTrendRes.getMsg());
                            if (pageNum == 1)
                            {
                                refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                            } else
                            {
                                refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                            }
                        }
                    }

                    @Override
                    public void onFailure(String json) {
                        if (pageNum == 1)
                        {
                            refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                        } else
                        {
                            refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                        }
                        try {
                            JSONObject object = new JSONObject(json);
                            String msg = object.getString("msg");
                            mainActivity.showToast(msg);
                        } catch (JSONException e) {
                            e.printStackTrace();
                            mainActivity.showToast("系统异常");
                        }
                    }
                });
    }
}
